<?php
/*
 * MinPlan "API"
 * Code: wizt, anemos, ThanE
 * REMEMBER: /tbody/ SHOULD NOT be used in xPath, just skip it
 */

// Magic mushroom
class scraper {
	function addExam($row) {

        $this->get($this->mainPage."courseLOV.do?actionDispatch=course_lov_view_select&selectedCourseSearchStateScope=active&courseLOVListHandler.page[".$row."].selected=on");

    }

    function searchExam($code,$years=null,$period=null) {
        /* TODO!
        * You can't search on the semester/period directly yet.
        * $code should be in format xxxxx.x NOT xxxxx.x.x
        */
        $this->getExams();
        $this->get("https://minplan.abo.fi/minplan/myRegistrationsMyExaminationRegistrations.do?actionDispatch=my_registrations_my_examination_registrations_add_course_to_lov");
        $results = $this->get($this->mainPage."courseLOV.do?".$this->searchExam."&courseCode=".$code);
        $this->lastPage = 'courseLOV.do';

        return $results;
    }

    function searchCourse($name, $years=null, $period=null, $page=null) {

        $name = str_replace(" ","+",$name);
        $this->getCourses();
        $this->get("https://minplan.abo.fi/minplan/myRegistrationsMyCourseRegistrations.do?actionDispatch=my_registrations_my_course_registrations_add_course_to_lov");
        $results = $this->get("https://minplan.abo.fi/minplan/courseLOV.do?actionDispatch=course_lov_view_search&identifier=".$page."&courseSearchCriteria.yearCode=".$years."&courseSearchCriteria.freetext=".$name."");
        $results = $this->get($this->mainPage."courseLOV.do?actionDispatch=%2Fga_list_handler_paging_loadondemand.do&identifier=".$page."&listHandlerName=fi.abo.minplan.web.formbean.CourseLOVForm&listHandlerProperty=courseLOVListHandler");
        return $results;
    }

    function scrapeSearchedExam($html) {

        // TODO: This should return a list of exam objects to make it easier to handle
        $exams = xPathify($html,'/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/div/table/tr[2]/td[2]/table[1]/tr[1]/td/table/tr');
        print "<br/>Det finns ".($exams->length-1)." tillgänglig(a) för denna kurs<br/>";

		global $currentPage;
        for ($i=1;$i<$exams->length;$i++) {
            $split = explode(')',$exams->item($i)->nodeValue);
            print "Kurs: ".$split[0].") Tent typ:".$split[1]."|  <a href=\"".$currentPage."?action=register&amp;row=".($i-1)."\">Anmäl dig</a> ";
        }

    }

    function scrapeSearchedCourse($html, $pages=null) {
        /*
         * TODO:
         * "Anmäl dig" button
         */


        // Gets the number of spans that are shown in the result
        // html/body/form/table/tbody/tr[2]/td[3]/table/tbody/tr[4]/td/div/div/div/table/tbody/tr[2]/td[2]/table[1]/tbody/tr[2]/td[1]

        $links = xPathify($html, '/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/div/table/tr[2]/td[2]/table[1]/tr[2]/td/span')->length;
        // Nice and short line here, if there are more pages, then this
        // runs xpath, then takes the attribute 'onclick' from the xpathed result
        // explodes it so that we only get the number of pages
        // removes all 's from the string so we get a integer and not a string
        if ($links>0 && $pages==null){
            $pages = str_replace("'", "", explode(',',(xPathify($html, '/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/div/table/tr[2]/td[2]/table[1]/tr[2]/td/span['.$links.']')->item(0)->getAttribute('onclick'))));
            $pages = $pages[1];

        }
        $courses = xPathify($html, '/html/body/form/table/tr[2]/td[3]/table/tr[4]/td/div/div/div/table/tr[2]/td[2]/table[1]/tr[1]/td/table/tr');
        for ($i=1; $i<$courses->length ;$i++) {
            print ''.$courses->item($i)->nodeValue.'| <a href=#>Anmäl dig</a><br/>';
        }

		global $currentPage;
        if ($pages>0) {
            print "Number of pages found: ".$pages."<br/>";
            for ($i=1;$i<=$pages;$i++) {
                if ($i != $_GET['p']){
                    if(isset($_POST['course']))
                    print '<a href="'.$currentPage.'?action=searchCourse&amp;course='.$_POST['course'].'&amp;p='.$i.'&amp;maxp='.$pages.'">'.$i.'</a> ';
                    else
                    print '<a href="'.$currentPage.'?action=searchCourse&amp;course='.$_GET['course'].'&amp;p='.$i.'&amp;maxp='.$pages.'">'.$i.'</a> ';

                }
                else print $i." ";
            }
        }
        else print "Only one page found";


    }

}

$scraper = new scraper();
if (isset($_GET['logout'])) {
  $user->logout();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><?php include("head.php");?> 
<body><?php
if (isset($_GET['login']) && $_SERVER["REQUEST_METHOD"] == 'POST') {
  $username = $_POST['username'];
  $password = $_POST['password'];
  $user->login($username, $password);
}
if(!$user->isLoggedIn()){
	include('login.html');
	include('help.html');
} else {
	include('menu.php');?> 
	<div id="wrapper">
		<div id="site"><?php
	if(isset($_GET['action'])) {
		switch($_GET['action']) {
			
		case 'searchExam':
				if (isset($_GET['course'])) {
				    $courseCode = substr($_GET['course'], 0, 8);
				    $scraper->scrapeSearchedExam($scraper->searchExam($courseCode));
				}
			break;
			
		case 'searchCourse':
			    $pageNr=1;
			    if (isset($_GET['p'])) {
			        $pageNr=$_GET['p'];
			    }
			    echo '<form name="mp_course_search" action="?action=searchCourse&p=1" method="POST" enctype="multipart/form-data">';
			    echo 'Kurs: <input type="text" name="course" /> <br/>';
			    echo 'Läsår: <select name="years">';
			    echo '<option value="">Alla</option>';
			    echo '<option value="20082009">2008-2009</option>';
			    echo '<option value="20092010">2009-2010</option>';
			    echo '<option value="20102011">2010-2011</option>';
			    echo '<option value="20112012">2011-2012</option>';
			    echo '<option value="20122013">2012-2013</option>';
			    echo '</select>';
			    echo '<br/><input type="submit" value="Sök">';
			    echo '</form>';
			
			    if (isset($_POST['course'])) {
			    	$years = isset($_POST['years']) ? $_POST['years'] : null;
			        $scraper->scrapeSearchedCourse($scraper->searchCourse($_POST['course'], $_POST['years'], null, $pageNr));
			    }
			    if (isset($_GET['course'])) {
			    	$years = isset($_GET['years']) ? $_GET['years'] : null;
			        $scraper->scrapeSearchedCourse($scraper->searchCourse($_GET['course'], $years, null, $pageNr),$_GET['maxp']);
			    }
			break;
			
		case 'register':
				$scraper->addExam(($_GET['row']));
		        echo "<b>Tentamen har lagts till!</b>";
		        $content = $scraper -> getCourses();
			    $scraper->createCList($content);
			break;
        
          case 'search':
		
			/*
			*This will be rewritten when anemos "knows" that his page_handler is working prop.
			*/
		
			// What is beeing searched ? (this should e a function)
			// RegEx for "knowing" if the user is searching with a code or freetext:
			//preg_match("/^(\d{5,6}).(\d)$/", $_POST['searchF'])
			
			// Assumes that the user wants courses that going now
			$cur_year = date(Y)."".(date(Y)+1);
			if ($_POST['courses']=='on' || $_POST['Sall']=='on') {
				$scraper->scrapeSearchedCourse($scraper->searchCourse($_POST['searchF'], $cur_year, null,1));
			}
			if ($_POST['exams']=='on') {
				
			}
			
			break;
		
		default:
			break;
		}
	}?> 
		</div>
	</div><?php
}?> 
</body>
</html>
